package com.hjb.service.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

public class PostUtil {

	/**
     * 向指定 URL 发送POST方法的请求
     * 
     * @param url
     *            发送请求的 URL
     * @param param
     *            请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
	 * @throws Exception 
     */
    public static String sendPost(String url, Map<String, String> params, String encode) throws Exception {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("content-type", "application/x-www-form-urlencoded;");  
          
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            
            
            StringBuffer stringBuffer = new StringBuffer();
            for (Map.Entry<String, String> entry : params.entrySet()) { 
             try { 
              stringBuffer 
                .append(entry.getKey()) 
                .append("=") 
                .append(URLEncoder.encode(entry.getValue(), encode)) 
                .append("&");

             } catch (UnsupportedEncodingException e) { 
              e.printStackTrace(); 
             }
            } 
            
            // 发送请求参数
            out.print(stringBuffer.toString());
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream(),encode));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常！"+e);
            e.printStackTrace();
            throw e;
        }
        //使用finally块来关闭输出流、输入流
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
        }
        System.out.println(result);
        return result;
    }    
    
	/**
	 * @param args
	 */
	public static String sendGet(String reqUrl, Map<String, String> params, String encode) {
		
		URL url = null;
		OutputStream outStrm = null;
		InputStream inStrm = null;
		BufferedReader br = null;
		String result = null;
		String temp = null;
		HttpURLConnection httpurlconnection = null;
		try {
            StringBuffer stringBuffer = new StringBuffer();
            for (Map.Entry<String, String> entry : params.entrySet()) { 
             try { 
              stringBuffer 
                .append(entry.getKey()) 
                .append("=") 
                .append(URLEncoder.encode(entry.getValue(), encode)) 
                .append("&");

             } catch (UnsupportedEncodingException e) { 
              e.printStackTrace(); 
             }
            } 
			url = new URL(reqUrl+"?"+stringBuffer.toString());
			httpurlconnection = (HttpURLConnection) url.openConnection();
			httpurlconnection.setDoInput(true);
			httpurlconnection.setDoOutput(true);
			httpurlconnection.setUseCaches(false);
			httpurlconnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;");  
			httpurlconnection.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");  
			httpurlconnection.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3");
			httpurlconnection.setRequestProperty("Connection", "keep-alive");
			httpurlconnection.setRequestProperty("Host", "v2.neeq.com.cn");
			httpurlconnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:42.0) Gecko/20100101 Firefox/42.0");
			httpurlconnection.setRequestProperty("X-Requested-With", "XMLHttpRequest");
			
			httpurlconnection.setRequestMethod("GET");
			System.out.println("httpurlconnection==" + httpurlconnection);
			httpurlconnection.connect();
			outStrm = httpurlconnection.getOutputStream();
			outStrm.flush();
			outStrm.close();
			inStrm = httpurlconnection.getInputStream();
			br = new BufferedReader(new InputStreamReader(
					inStrm, "UTF-8"));
			while ((temp = br.readLine()) != null) {
				result = result + temp;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			try {
				inStrm.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return "";
	}
	

	
	/**
	 * @param args
	 * @throws Exception 
	 */
	public static void main(String[] args) throws Exception {
		String url = "http://api.shuyuanwl.com:8080/api/sms/send?";
		Map<String, String> params = new HashMap<String, String>();
		params.put("account", "tjhthy@tjhthy");
		params.put("password", "sh64MT92");
		params.put("mobiles", "17600901605");
		params.put("content", "8888 手机注册验证码，请于60秒内输入，请勿告诉任何人");
		
		
		String result = PostUtil.sendPost(url, params, "UTF-8");
		System.out.println(result);
		
        
	}

    	
}
